package com.zhudi.utils;

import com.zhudi.config.RedisConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public final class RedisUtil {
    
    // 此处自动注入参数是上述自己定义的RedisTemplate,而非默认的

    private static  RedisTemplate<String, Object> redisTemplate  ;
    @Resource
    private RedisConfig redisConfig;
    @Autowired
    private RedisConnectionFactory factory;

    //使用PostConstruct注解让Spring在启动的时候初始化一下RedisUtils，解决自动注入不能注入静态类的问题
    @PostConstruct
    public void init() {
        redisTemplate = redisConfig.redisTemplate(factory);
    }



    /**
     * 取
     * @param key 键
     * @return
     */
    public static Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
 
    /**
     * 普通缓存放入
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public static boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * set并且指定缓存失效时间
     * @param key  键
     * @param value 值
     * @param time 时间(秒)
     * @return 成功true
     */
    public static boolean set(String key, Object value, long time) {
        try {
            redisTemplate.opsForValue().set(key, value,time, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.error("redis set key: "+key+" error");
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 指定缓存失效时间
     * @param key  键
     * @param time 时间(秒)
     * @return 成功true
     */
    public static boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public static long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
}